package com.JFapp.service.impl;

import com.JFapp.domain.dto.*;
import com.JFapp.domain.entity.ResponseResult;
import com.JFapp.domain.entity.User;
import com.JFapp.domain.vo.PageVo;
import com.JFapp.domain.vo.UserDetailVo;
import com.JFapp.domain.vo.UserInfoVo;
import com.JFapp.mapper.UserMapper;
import com.JFapp.service.RoleService;
import com.JFapp.service.UserService;
import com.JFapp.utils.SecurityUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.JFapp.utils.BeanCopyUtils.copyBean;

/**
 * 计服用户表(User)表服务实现类
 *
 * @author makejava
 * @since 2023-11-08 23:32:11
 */
@Service("jfUserService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RoleService roleService;

    @Override
    public ResponseResult register( User user) {
        String encode=passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        save(user);
        return ResponseResult.okResult();
    }

    @Override
    public User getByName(String name) {
        LambdaQueryWrapper<User> wrapper= new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> eq = wrapper.eq(User::getUserName, name);
        User user = getOne(eq);
        return user;
    }

    @Override
    public String selectPhone(Long userId) {
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> eq = wrapper.select(User::getPhoneNum).eq(User::getId, userId);
        User user = getOne(eq);
        return user.getPhoneNum();
    }

    @Override
    public ResponseResult selectUserInfo() {
        //获取id
        Long userId = SecurityUtils.getUserId();
        User user=getById(userId);
        UserInfoVo userInfoVo = copyBean(user, UserInfoVo.class);
        return ResponseResult.okResult(userInfoVo);
    }

    @Override
    public ResponseResult updateUserInfo(User user) {
        if (StringUtils.hasText(user.getPassword())){
            String encode=passwordEncoder.encode(user.getPassword());
            user.setPassword(encode);
        }
        LambdaUpdateWrapper<User> updateWrapper=new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId,SecurityUtils.getUserId());
        update(user,updateWrapper);
        return ResponseResult.okResult();
    }

    @Override
    public Long selectID(String userName) {
        Long uid=baseMapper.selectIdByName(userName);
        return uid;
    }

    @Override
    public List<Long> selectIDs(List<String> userName) {
        List<Long> ids =  baseMapper.selectByNames(userName);
        return ids;
    }

    @Override
    public ResponseResult selectAllUser(Integer pageNum,Integer pageSize) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> wrapper = queryWrapper.select(User::getId, User::getUserName, User::getNickName, User::getPhoneNum, User::getEmail, User::getStatus);
        Page page =new Page<>(pageNum,pageSize);
        page(page,wrapper);
        List<User> user = page.getRecords();
        PageVo pageVo=new PageVo(user,page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult changeUserStatus(ChangeUserStatusDto changeUserStatusDto) {
        LambdaUpdateWrapper<User> updateWrapper =new LambdaUpdateWrapper<>();
        LambdaUpdateWrapper<User> wrapper = updateWrapper.set(User::getStatus, changeUserStatusDto.getStatus()).eq(User::getId, changeUserStatusDto.getId());
        update(wrapper);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getUserDetail(Long userId) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> wrapper = queryWrapper.select(User::getId,User::getUserName,User::getNickName
                        ,User::getPhoneNum,User::getSex,User::getEmail, User::getStatus)
                .eq(User::getId,userId);
        User user = getOne(wrapper, false);
        List<Long> roleId=roleService.selectRoleIdByUserId(userId);
        UserDetailVo userDetailVo = copyBean(user, UserDetailVo.class);
        userDetailVo.setRoleIds(roleId);
        return ResponseResult.okResult(userDetailVo);
    }

    @Override
    public ResponseResult updateUser(UserDetailDto userDetailDto) {
        User user = copyBean(userDetailDto, User.class);
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        LambdaUpdateWrapper<User> updateWrapper=new LambdaUpdateWrapper<>();
        LambdaUpdateWrapper<User> wrapper = updateWrapper.eq(User::getId, user.getId());
        update(user,wrapper);
        roleService.updateRoleAndUser(user.getId(),userDetailDto.getRoleIds());
        return ResponseResult.okResult();
    }

    @Override
    public Map<Long, String> getIdAndNameById(List<Long> userIds) {
        List<Map<String, Object>> results = baseMapper.getNamesById(userIds);
        return results.stream()
                .collect(Collectors.toMap(
                        map -> (Long) map.get("id"),
                        map -> (String) map.get("user_name")
                ));

    }

    @Override
    public ResponseResult getUserByFuzzy(UserByFuzzyDto userDetailDto) {
        LambdaQueryWrapper<User> lambdaQueryWrapper= new LambdaQueryWrapper<>();
            LambdaQueryWrapper<User> wrapper = lambdaQueryWrapper
                    .or().like(StringUtils.hasText(userDetailDto.getUserName()),User::getUserName, userDetailDto.getUserName())
                    .or().like(StringUtils.hasText(userDetailDto.getPhoneNum()),User::getPhoneNum,userDetailDto.getPhoneNum())
                    .or().like(StringUtils.hasText(userDetailDto.getStatus()),User::getStatus,userDetailDto.getStatus());
            List<User> list = list(wrapper);

        return ResponseResult.okResult(list);
    }


//    @Override
//    public ResponseResult resetPwdById(ResetPwdDto resetPwdDto) {
//        String npassword = passwordEncoder.encode(resetPwdDto.getPassword());
//        LambdaUpdateWrapper<User> updateWrapper=new LambdaUpdateWrapper<>();
//        LambdaUpdateWrapper<User> wrapper = updateWrapper.set(User::getPassword, npassword).eq(User::getId, resetPwdDto.getUserId());
//        update(wrapper);
//        return ResponseResult.okResult();
//    }

    @Override
    public User findUserByEmail(String email) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> queryWrapper1 = queryWrapper.eq(User::getEmail, email);;
        return this.getOne(queryWrapper1,false);
    }

    @Override
    public User findUserByPhone(String phone) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        LambdaQueryWrapper<User> queryWrapper1 = queryWrapper.eq(User::getPhoneNum, phone);
        return this.getOne(queryWrapper1,false);
    }


}
